package com.zl.gmadmin.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zl.gmadmin.entity.BlogLabel;
import com.zl.gmadmin.exception.BaseException;
import com.zl.gmadmin.payload.BlogArticleQueryCriteria;
import com.zl.gmadmin.service.BlogLabelService;
import com.zl.gmadmin.utils.PageUtils;
import com.zl.gmadmin.entity.BlogArticle;
import com.zl.gmadmin.mapper.BlogArticleMapper;
import com.zl.gmadmin.service.BlogArticleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ZhangLiang
 * @Date: 2021/08/24/12:49
 * @Description:
 */
@Service
public class BlogArticleServiceImpl extends ServiceImpl<BlogArticleMapper, BlogArticle> implements BlogArticleService {

    private final BlogArticleMapper blogArticleMapper;
    private final BlogLabelService blogLabelService;

    public BlogArticleServiceImpl(BlogArticleMapper blogArticleMapper, BlogLabelService blogLabelService) {
        this.blogArticleMapper = blogArticleMapper;
        this.blogLabelService = blogLabelService;
    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public Object selectPageVo(BlogArticleQueryCriteria queryCriteria, Page<BlogArticle> page) {
        QueryWrapper<BlogArticle> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(queryCriteria.getTypeName())&&!queryCriteria.getTypeName().equals("all")) {
            queryWrapper.eq("name", queryCriteria.getTypeName());
        }
//        获取排序字段
        String columns = queryCriteria.getSort().stream().map(s -> s.equals("id") ? "article_id" : s).filter(s -> !s.contains("desc") && !s.contains("asc")).collect(Collectors.joining(","));
        //获取排序方式是asc还是desc
        String order = queryCriteria.getSort().get(queryCriteria.getSort().size() - 1);
        queryWrapper.orderBy(true, order == "asc" ? true : false, columns);
        queryWrapper.groupBy("article_id");

        IPage<BlogArticle> blogArticleIPage = blogArticleMapper.selectPage(page, queryWrapper);
        List<BlogArticle> blogArticles = blogArticleIPage.getRecords();
        System.out.println(JSONUtil.toJsonStr(blogArticles));
        return PageUtils.toPage(blogArticles, blogArticleIPage.getTotal());
    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public void saveBlogArticle(BlogArticle blogArticle) {
        blogArticleMapper.insert(blogArticle);
        //        保存标签id
        List<Long> blogLabelIds = new ArrayList<>();
//        查询出所有的标签,判断是否存在，存在就找到id，不存在就新增
        List<BlogLabel> blogLabels = blogLabelService.getAll();

        List<String> labels = blogLabels.stream().map(blogLabel -> blogLabel.getLabelName()).collect(Collectors.toList());

        if (Objects.isNull(blogArticle.getBlogLabels())) {
        } else {
            for (int i = 0; i < blogArticle.getBlogLabels().size(); i++) {
                BlogLabel blogLabel = blogArticle.getBlogLabels().get(i);
                for (BlogLabel b : blogLabels
                ) {
                    //      如果存在并且传送数据缺少id,就需要找到
                    if (b.getLabelName().equals(blogLabel.getLabelName()) && Objects.isNull(blogLabel.getId())) {
                        blogLabel.setId(b.getId());
//                    System.out.println("我是存在就获取id");
                    } else if (Objects.nonNull(blogLabel.getId())) {
//                    System.out.println("我是本来就有的");
                    } else if (!labels.contains(blogLabel.getLabelName())) {
//                    System.out.println("我是需要新增的");
                        blogLabelService.save(blogLabel);
                    }
                }
                blogLabelIds.add(blogLabel.getId());

            }

            System.out.println("标签id:  " + blogLabelIds);

//        先删除原来的中间表,新增不需要
//        blogArticleMapper.deleteArticleAndLabel(blogArticle.getId());
//        中间表保存
            if (blogLabelIds.size()>0) {
                blogArticleMapper.insertArticleAndLabel(blogArticle.getId(), blogLabelIds);
            }
        }
    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        blogArticleMapper.deleteArticleAndLabel(idList);
        blogArticleMapper.deleteBatchIds(idList);
        return true;
    }

    @Transactional(rollbackFor = BaseException.class)
    @Override
    public void updateBlogArticle(BlogArticle blogArticle) {
        blogArticleMapper.updateById(blogArticle);
        //        保存标签id
        List<Long> blogLabelIds = new ArrayList<>();
//        查询出所有的标签,判断是否存在，存在就找到id，不存在就新增
        List<BlogLabel> blogLabels = blogLabelService.getAll();

        List<String> labels = blogLabels.stream().map(blogLabel -> blogLabel.getLabelName()).collect(Collectors.toList());

        if (Objects.isNull(blogArticle.getBlogLabels())) {
        } else {
            for (int i = 0; i < blogArticle.getBlogLabels().size(); i++) {
                BlogLabel blogLabel = blogArticle.getBlogLabels().get(i);
                for (BlogLabel b : blogLabels
                ) {
                    //      如果存在并且传送数据缺少id,就需要找到
                    if (b.getLabelName().equals(blogLabel.getLabelName()) && Objects.isNull(blogLabel.getId())) {
                        blogLabel.setId(b.getId());
//                    System.out.println("我是存在就获取id");
                    } else if (Objects.nonNull(blogLabel.getId())) {
//                    System.out.println("我是本来就有的");
                    } else if (!labels.contains(blogLabel.getLabelName())) {
//                    System.out.println("我是需要新增的");
                        blogLabelService.save(blogLabel);
                    }
                }
                blogLabelIds.add(blogLabel.getId());

            }

            System.out.println("标签id:  " + blogLabelIds);

//        先删除原来的中间表,新增不需要
            blogArticleMapper.deleteArticleAndLabel(Collections.singleton(blogArticle.getId()));
//        中间表保存
            blogArticleMapper.insertArticleAndLabel(blogArticle.getId(), blogLabelIds);
        }
    }
}
